package com.android.tutos;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.media.AudioManager;
import android.media.SoundPool;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

class Panel extends SurfaceView implements SurfaceHolder.Callback {

	private GraphicThread _thread;

    private Path path;    
    private SoundPool _soundPool;
    private SoundPool _playbackFile;
    
	private ArrayList<Path> _graphics = new ArrayList<Path>();  
	private Paint mPaint;
	
    
	
	public Panel(Context context) {
		super(context);
		
		//_soundPool = new SoundPool(16, AudioManager.STREAM_MUSIC, 100);
	    //_playbackFile = _soundPool.load(getContext(), R.raw.explosion, 0);
		mPaint = new Paint();  
		mPaint.setDither(true);  
		mPaint.setColor(0xFFFF5555);  
		mPaint.setStyle(Paint.Style.STROKE);  
		mPaint.setStrokeJoin(Paint.Join.BEVEL);  
		mPaint.setStrokeCap(Paint.Cap.BUTT);  
		mPaint.setStrokeWidth(15);  
	    getHolder().addCallback(this);
	    _thread = new GraphicThread(getHolder(), this);
	    setFocusable(true);
	}

	@Override
	public void onDraw(Canvas canvas) {
		 for (Path path : _graphics) {  
			    //canvas.drawPoint(graphic.x, graphic.y, mPaint);  
			    canvas.drawPath(path, mPaint);  
			  } 
	}

	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void surfaceCreated(SurfaceHolder arg0) {
		_thread.setRunning(true);
	    _thread.start();
		
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		// simply copied from sample application LunarLander:
	    // we have to tell thread to shut down & wait for it to finish, or else
	    // it might touch the Surface after we return and explode
	    boolean retry = true;
	    _thread.setRunning(false);
	    while (retry) {
	        try {
	            _thread.join();
	            retry = false;
	        } catch (InterruptedException e) {
	            // we will try it again and again...
	        }
	    }
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		synchronized (_thread.getSurfaceHolder()) {  
		    if(event.getAction() == MotionEvent.ACTION_DOWN){  
		      path = new Path();  
		      path.moveTo(event.getX(), event.getY());  
		      path.lineTo(event.getX(), event.getY());  
		    }else if(event.getAction() == MotionEvent.ACTION_MOVE){  
		      path.lineTo(event.getX(), event.getY());
		      _graphics.add(path);
		    }else if(event.getAction() == MotionEvent.ACTION_UP){  
		      path.lineTo(event.getX(), event.getY());  
		      _graphics.add(path);  
		    }  
		    return true;  
		  }
	}
		
	
}
